﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AjaxUploadServer
{
	public struct ClientFile
	{
		public string name;
		public string type;
		public string hash;
		public UInt64 size;
		public UInt64 lastModified;

		[Newtonsoft.Json.JsonIgnore]
		public bool IsEmpty
		{
			get
			{
				return String.IsNullOrEmpty(json)
					|| String.IsNullOrEmpty(name)
					|| String.IsNullOrEmpty(type)
					|| size < 1
					;
			}
		}

		[Newtonsoft.Json.JsonIgnore]
		public string json;

		public const int BufferSize = ushort.MaxValue;

		public override string ToString()
		{
			return Newtonsoft.Json.JsonConvert.SerializeObject(this);
		}
		public static ClientFile Create(string json)
		{
			ClientFile client;
			try
			{
				client = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientFile>(json);
				client.json = json;
			}
			catch
			{
				client = new ClientFile();
				client.json = null;
			}
			return client;
		}
		public static ClientFile Create(System.IO.Stream stream)
		{
			byte[] buffer = new byte[BufferSize];
			int readLen = stream.Read(buffer, 0, buffer.Length);
			var json = System.Text.Encoding.UTF8.GetString(buffer, 0, readLen);
			return Create(json);
		}
		public static ClientFile Create(HttpRequestBase request)
		{
			ClientFile client;
			using (var stream = request.GetBufferlessInputStream())
			{
				client = Create(stream);
			}
			return client;
		}
		public static ClientFile CreateFromFile(string filename)
		{
			if (String.IsNullOrEmpty(filename) || !System.IO.File.Exists(filename))
				return new ClientFile();
			var json = System.IO.File.ReadAllText(filename, System.Text.Encoding.UTF8);
			return Create(json);
		}
	}
}